#!/bin/sh
#
# $FreeBSD$
#

# PROVIDE: ix-snmpd
# REQUIRE: FILESYSTEMS NETWORKING
# REQUIRE: openssh
# BEFORE: snmpd

. /etc/rc.subr

snmp_config=/etc/local/snmpd.conf

generate_snmpconf()
{
	local IFS="|"
	local f="snmp_location snmp_contact snmp_community snmp_v3 snmp_v3_username snmp_v3_authtype snmp_v3_password snmp_v3_privproto snmp_v3_privpassphrase"
	eval local $f
	local sf=$(var_to_sf $f)
	RO_FREENAS_CONFIG=$(ro_sqlite ${name} 2> /tmp/${name}.fail && rm /tmp/${name}.fail)
	trap 'rm -f ${RO_FREENAS_CONFIG}' EXIT

	umask 077
	hw_machine=`/sbin/sysctl -n hw.machine`
	hw_model=`/sbin/sysctl -n hw.model`
	hw_clockrate=`/sbin/sysctl -n hw.clockrate`
	kern_ostype=`/sbin/sysctl -n kern.ostype`
	kern_osrelease=`/sbin/sysctl -n kern.osrelease`
	kern_osrevision=`/sbin/sysctl -n kern.osrevision`
	freenas_version=`cat /etc/version`

	local snmp_options=$(${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "SELECT snmp_options FROM services_snmp ORDER BY -id LIMIT 1")
	${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "SELECT $sf FROM services_snmp ORDER BY -id LIMIT 1" | \
	while eval read -r $f; do
		cat > "${snmp_config}" << EOF
agentAddress udp:161,udp6:161,unix:/var/run/snmpd.sock
sysLocation ${snmp_location:-unknown}
sysContact ${snmp_contact:-unknown@localhost}
sysDescr ${freenas_version}. Hardware: ${hw_machine} ${hw_model} running at ${hw_clockrate}. Software: ${kern_ostype} ${kern_osrelease} (revision ${kern_osrevision})

master agentx
EOF

		if [ ${snmp_v3} -eq 1 ]; then

			if [ "${snmp_v3_username}" != "" -a "${snmp_v3_password}" != "" ]; then
				echo -n "createUser ${snmp_v3_username}	${snmp_v3_authtype} \"${snmp_v3_password}\"" >> ${snmp_config}
				if [ -n "${snmp_v3_privproto}" -a -n "${snmp_v3_privpassphrase}" ]; then
					echo " ${snmp_v3_privproto} \"${snmp_v3_privpassphrase}\"" >> ${snmp_config}
				else
					echo >> ${snmp_config}
				fi
				echo "rwuser ${snmp_v3_username}" >> ${snmp_config}
			fi

		else
			echo "rocommunity \"${snmp_community}\" default" >> ${snmp_config}
			# Below line required for SNMP over IPv6 -- the strings are not the same!
			echo "rocommunity6 \"${snmp_community}\" default" >> ${snmp_config}
		fi

		echo "${snmp_options}" >> ${snmp_config}
	done
}

name="ix-snmpd"
start_cmd='generate_snmpconf'
stop_cmd=':'

load_rc_config $name
run_rc_command "$1"
